<template>
  <div ref="boxRef" class="h-full w-full">
    <!-- <canvas ref="qrcodeRef" /> -->
    <img :src="imgUrl" class="h-full w-full" alt="">
  </div>
</template>

<script lang="ts" setup>
import QRCode from 'qrcode'
import { showToast } from 'vant'

interface Props {
  text?: string
}

const props = withDefaults(defineProps<Props>(), {
  text: '',
})

// const qrcodeRef = ref<HTMLCanvasElement>()
const boxRef = ref<HTMLDivElement>()
const imgUrl = ref('')
async function generateQRCode() {
  try {
    await nextTick()
    // if (!qrcodeRef.value || !boxRef.value) {
    //   return
    // }
    if (!boxRef.value) {
      return
    }
    const width = boxRef.value.clientWidth
    // QRCode.toCanvas(qrcodeRef.value, props.text, {
    //   margin: 0,
    //   width,
    // })
    QRCode.toDataURL(props.text, {
      margin: 0,
      width,
    }).then((url) => {
      imgUrl.value = url
    })
  }
  catch (err) {
    console.error(err)
  }
}

function inWeihart() {
  const ua = navigator.userAgent.toLowerCase()
  const isWeixin = ua.includes('micromessenger')
  if (isWeixin) {
    return true
  }
  else {
    return false
  }
}

function save() {
  if (!imgUrl.value) {
    return
  }
  if (inWeihart()) {
    showToast('请长按二维码进行保存！')
    return
  }
  const link = document.createElement('a')
  link.href = imgUrl.value
  link.download = '商品兑换二维码.png'
  link.click()
}

onMounted(() => {
  watch(
    () => props.text,
    (val) => {
      if (val) {
        generateQRCode()
      }
    },
    { immediate: true },
  )
})

defineExpose({
  save,
})
</script>

<style lang="scss" scoped></style>
